import Qs from 'qs'
import Vue from 'vue'
import jwt_decode from "jwt-decode";

/*
$.ajax({
  type: "POST",
  url: "/user/list",
  data: {
    key: value,
    key2: value2
  },
  success: function(data) {

  }
});

{
      method: param.type ? param.type : "GET",
      url: "http://localhost:8080" + param.url,
      //GET
      params: param.data

      //POST
      transformRequest: [function (data) {
        return Qs.stringify(data)
      }],
      data: param.data
    }
*/
export default {
  baseUrl: "http://127.0.0.1",
  //websocket服务器的连接地址
  wsUrl: "ws://127.0.0.1:20000/",
  //websocket的连接对象
  ws: null,
  getImgUrl(fileName){
    return this.baseUrl + "/user/img/download?fileName=" + fileName;
  },
  ajax(param){
    //开启页面加载
    const loading = Vue.prototype.$loading({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    //设置axios的请求参数
    var axiosParam = {};
    axiosParam.timeout = 2000;

    //设置method的属性
    axiosParam.method = param.type ? param.type : "GET";
    //设置url属性
    axiosParam.url = this.baseUrl + param.url;
    //设置参数的属性
    if(param.data) {

    if(param.type && param.type == "POST"){
        //发送post请求
        axiosParam.transformRequest = [function (data) {
          return Qs.stringify(data)
        }];
        axiosParam.data = param.data;
      } else {
        //发送get请求
        axiosParam.params = param.data;
      }
    }

    //准备一个请求头
    var header = {};

    //判断是否上传
    if(param.uploader){
      header["Content-Type"] = 'multipart/form-data';
    }

    //额外设置两个参数 1、登录的令牌  2、fromType - 0 教师端 1 学生端
    // header.fromType = 1;
    var jwtToken = this.getUserToken();
    var type = this.getType();
    if(jwtToken){
      //有登录令牌
      header.loginToken = jwtToken;
    }
    if(type){
      header.fromType = type;
    }
    axiosParam.headers = header;

    Vue.axios(axiosParam).then((result) => {
      var data = result.data.data;
      console.log("请求成功！", data);
      if(param.success) {
        //调用success方法
        param.success(data, result.data.page);
      }
    }).catch((result) => {
      console.log("请求失败！", result);
      if(result.response){
        var data = result.response.data;

        if(data.code == 401){
          //参数校验异常
          var errors = data.data;
          //循环处理
          var msg = "";
          for(var i = 0; i < errors.length; i++){
            msg += (errors[i] + "\n\r");
          }
          Vue.prototype.$notify.error({
            title: data.msg,
            message: msg
          });
        } else if(data.msg) {
          //弹窗将错误信息弹出
          Vue.prototype.$message.error(data.msg + (data.data ? data.data : ""));
        }
      } else {
        Vue.prototype.$message.error("服务器繁忙，请稍后再试！");
      }
    }).then(function () {
      // 总是会执行
      //关闭加载
      loading.close();
    });
  },
  saveUserToken(jwtToken){
    //保存jwt令牌到浏览器本地
    localStorage.setItem("userToken", jwtToken);
  },
  saveType(fromType) {
    localStorage.setItem("fromType", fromType);
  },
  getUserToken(){
    //返回jwt令牌
    return localStorage.getItem("userToken");
  },
  getType(){
    //返回jwt令牌
    return localStorage.getItem("fromType");
  },
  removeToken(){
    //删除token
    localStorage.removeItem("userToken");
  },
  parseJwtToken(){
    //获取令牌
    var jwtToken = this.getUserToken();
    if(!jwtToken){
      return null;
    }
    //解析jwtToken
    var userInfo = jwt_decode(jwtToken).user;
    console.log("解析jwt令牌:", userInfo);
    //将json字符串 转换成 js对象
    return JSON.parse(userInfo);
  },
  //websocket 连接信令服务器
  wsInit(params){
    this.ws = new WebSocket(this.wsUrl);
    //设置ws回调方法
    this.ws.onopen = () => {
      console.log("信令服务器连接成功！");
      if(params && params.onopen) {
        //调用传递过来的方法
        params.onopen();
      }
    };

    this.ws.onmessage = (msg) => {
      console.log("接收到信令服务器的消息", msg.data);
      if(params && params.onmessage){
        params.onmessage(JSON.parse(msg.data));
      }
    }
    return this.ws;
  },
  //给WebSocket发送消息
  sendMsg(obj){
    if(this.ws){
      this.ws.send(JSON.stringify(obj));
    } else {
      console.log("WebSocket服务对象异常，发送消息失败！！");
    }
  }
}
